package com.ljh.mail;


import com.ljh.pojo.Employee;
import com.ljh.vo.MailConstants;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.springframework.messaging.Message;

import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @author ZSJia
 * @date 2021/8/19 019 - 12:57
 */
@Component
public class MailReceiver {

    private static  final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public  void handler(Message message,Channel channel) throws IOException {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);

        //获取员工实体类
        Employee emp = (Employee) message.getPayload();
        MessageHeaders headers = message.getHeaders();
        //获取序列号
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        //获取消息id（msgId)
        String msgId = (String) headers.get("spring_returned_message_correlation");
        //声明redis
        HashOperations hashOperations = redisTemplate.opsForHash();
        try {
            //判断redis是否存在msgId，如果有，直接返回
            if (hashOperations.entries("mail_log").containsKey(msgId)){
                LOGGER.error("消息已经消费过了============》{}",msgId);
                /**
                 * 收到确认
                 * tag：序列号
                 * multiple:是否确认多条
                 */
                channel.basicAck(tag,false);
                return;
            }
            //发件人
            helper.setFrom(mailProperties.getUsername());
            //邮箱地址
            helper.setTo(emp.getEmail());
            //日期
            helper.setSentDate(new Date());
            //主题
            helper.setSubject("入职欢迎邮件");
            //邮件内容
            Context context = new Context();
            context.setVariable("name",emp.getName());
            context.setVariable("posName",emp.getPosition().getName());
            context.setVariable("joblevelName",emp.getJoblevel().getName());
            context.setVariable("departmentName",emp.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);
            //发送邮件
            javaMailSender.send(msg);
            //加入redis
            hashOperations.put("mail_log",msgId,"ok");
            //手动回调
            channel.basicAck(tag,false);
        } catch (Exception e) {
            /**
             * 手动回调失败
             * tag：序号
             * false：是否批量处理
             * true：是否返回队列
             */
            channel.basicNack(tag,false,true);
                LOGGER.error("邮件发送失败======={}",e.getMessage());
        }
    }

}
